package com.yjy.fuyao.stu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.yjy.fuyao.stu.entity.dto.ExcelSubjectDTO;
import com.yjy.fuyao.stu.mapper.SubjectMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelSubjectDTOListener extends AnalysisEventListener<ExcelSubjectDTO> {

    private Integer BIND_COUNT = 10;

    private SubjectMapper subjectMapper;

    private List<ExcelSubjectDTO> list = new ArrayList<>();

    public ExcelSubjectDTOListener(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }

    @Override
    public void invoke(ExcelSubjectDTO excelSubjectDTO, AnalysisContext analysisContext) {
        list.add(excelSubjectDTO);
        log.info("开始读取文件");
        if(list.size() >= BIND_COUNT){
            saveData();
            log.info("已读取"+list.size()+"行数据");
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(list.size() >= 0){
            saveData();
            list.clear();
        }
        log.info("读取完成");
    }

    public void saveData(){
        subjectMapper.insertBatch(list);
    }

}
